using System;
using NUnit.Framework;
using System.Net.Sockets;
using System.Net;

namespace Tests.Server.Net {
    [TestFixture]
    public class ClientListenerTests {

        private bool TestConnection() {
            TcpClient client = new TcpClient();

            try {
                client.Connect(IPAddress.Loopback, 9001);
            }
            catch (SocketException) {
                return false;
            }

            return client.Connected;
        }

        [Test]
        public void ConnectionTest() {
            Slobby.Server.Net.ClientListener l = new Slobby.Server.Net.ClientListener();
            

            l.BeginListen();

            Assert.IsTrue(TestConnection(), "first open connection");            
            Assert.IsTrue(TestConnection(), "second open connection");

            l.EndListen();

            Assert.IsFalse(TestConnection(), "first closed connection");
        }


        volatile bool passed;

        [Test]
        public void EventTest() {
            Slobby.Server.Net.ClientListener l = new Slobby.Server.Net.ClientListener();
            passed = false;
            l.ClientConnected += delegate {
                passed = true;
            };

            l.BeginListen();

            TestConnection();

            System.Threading.Thread.Sleep(100);

            Assert.IsTrue(passed, "event was not fired");

            l.EndListen();
        }
    }
}
